<template>
  <div v-if="visible" class="fixed inset-0 bg-gray-800 bg-opacity-60 flex items-center justify-center z-50 p-4" @click.self="closeModal">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-lg mx-auto overflow-hidden transform transition-all duration-300 ease-out">
      <div class="bg-gradient-to-r from-emerald-500 to-green-500 text-white px-6 py-4 flex justify-between items-center">
        <h3 class="text-xl font-semibold tracking-tight">{{ foodDisplay.name || '食物详情' }}</h3>
        <button @click="closeModal" type="button" class="text-white hover:text-gray-200 transition-colors duration-150 focus:outline-none">
          <i class="fas fa-times fa-lg"></i>
        </button>
      </div>

      <div v-if="food" class="px-6 py-6 max-h-[75vh] overflow-y-auto styled-scrollbar">
        <div class="flex flex-col md:flex-row gap-6 mb-6 items-center md:items-start">
          <div class="w-40 h-40 md:w-48 md:h-48 flex-shrink-0">
            <img 
              :src="foodDisplay.image"
              alt="食物图片" 
              class="w-full h-full object-cover rounded-lg border border-gray-200 shadow-sm bg-gray-100"
              @error="onImageError"
            />
          </div>
          <div class="flex-grow space-y-2 text-center md:text-left">
            <p class="text-sm text-gray-500"><span class="font-medium text-gray-700">分类:</span> {{ foodDisplay.categoryName }}</p>
            <p class="text-sm text-gray-500"><span class="font-medium text-gray-700">计量单位:</span> {{ foodDisplay.unit }}</p>
            <p class="text-sm text-gray-500">
              <span class="font-medium text-gray-700">状态:</span> 
              <span :class="['font-semibold px-2 py-0.5 rounded-full text-xs', foodDisplay.isVerified ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700']">
                {{ foodDisplay.isVerified ? '已验证' : '未验证' }}
              </span>
            </p>
          </div>
        </div>

        <div class="space-y-5">
          <div>
            <h5 class="text-lg font-semibold text-emerald-600 mb-2 border-b pb-1">主要营养成分</h5>
            <div class="grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
              <p><span class="text-gray-600">热量:</span> <strong class="text-gray-800">{{ foodDisplay.calories }}</strong></p>
              <p><span class="text-gray-600">蛋白质:</span> <strong class="text-gray-800">{{ foodDisplay.protein }}</strong></p>
              <p><span class="text-gray-600">脂肪:</span> <strong class="text-gray-800">{{ foodDisplay.fat }}</strong></p>
              <p><span class="text-gray-600">碳水化合物:</span> <strong class="text-gray-800">{{ foodDisplay.carbohydrate }}</strong></p>
            </div>
          </div>

          <div>
            <h5 class="text-lg font-semibold text-emerald-600 mb-2 border-b pb-1">其他营养素</h5>
            <div class="grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
              <p><span class="text-gray-600">膳食纤维:</span> <strong class="text-gray-800">{{ foodDisplay.fiber }}</strong></p>
              <p v-if="foodDisplay.sugar !== '未提供'"><span class="text-gray-600">糖:</span> <strong class="text-gray-800">{{ foodDisplay.sugar }}</strong></p>
              <p v-if="foodDisplay.sodium !== '未提供'"><span class="text-gray-600">钠:</span> <strong class="text-gray-800">{{ foodDisplay.sodium }}</strong></p>
              <p v-if="foodDisplay.cholesterol !== '未提供'"><span class="text-gray-600">胆固醇:</span> <strong class="text-gray-800">{{ foodDisplay.cholesterol }}</strong></p>
            </div>
          </div>

          <div v-if="foodDisplay.notes && foodDisplay.notes !== '未提供'">
            <h5 class="text-lg font-semibold text-emerald-600 mb-2 border-b pb-1">备注</h5>
            <p class="text-sm text-gray-700 whitespace-pre-wrap leading-relaxed">{{ foodDisplay.notes }}</p>
          </div>
        </div>

        <div class="mt-8 pt-4 border-t border-gray-200 text-xs text-gray-500 space-y-1">
          <p v-if="foodDisplay.source && foodDisplay.source !== '未提供'"><span class="font-medium">数据来源:</span> {{ foodDisplay.source }}</p>
          <p><span class="font-medium">创建时间:</span> {{ foodDisplay.createdAt }}</p>
          <p><span class="font-medium">最后更新:</span> {{ foodDisplay.updatedAt }}</p>
           <!-- ID 仍然可以保留，但放在不显眼的位置，或只在开发模式下显示 -->
          <p class="mt-2"><span class="font-medium">内部ID:</span> {{ foodDisplay.id }}</p>
        </div>

      </div>
      <div v-else class="px-6 py-10 text-center text-gray-500">
        <i class="fas fa-search fa-2x text-gray-400 mb-2"></i>
        <p>正在加载食物数据或数据不存在...</p>
      </div>

      <div class="bg-gray-50 px-6 py-4 flex justify-end border-t">
        <button 
          @click="closeModal"
          type="button" 
          class="bg-emerald-600 hover:bg-emerald-700 text-white px-6 py-2 rounded-lg shadow-sm hover:shadow-md transition-all duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-opacity-50"
        >
          关闭
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { getFullFoodImageUrl as apiGetFullFoodImageUrl } from '@/api/foods';

const props = defineProps({
  food: {
    type: Object,
    default: () => null
  },
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['close']);

const closeModal = () => {
  emit('close');
};

const placeholderImageUrl = 'https://dummyimage.com/300x200/cccccc/000000.png&text=No+Image';

const onImageError = (event) => {
  event.target.src = placeholderImageUrl;
};

const formatNutrient = (value, unit = 'g') => {
  if (value === undefined || value === null || String(value).trim() === '') {
    return '未提供';
  }
  if (isNaN(Number(value))) return String(value); // 如果不是数字，直接返回原样
  return `${Number(value)}${unit}`;
};

const formatDate = (dateString) => {
  if (!dateString) return '未提供';
  try {
    return new Date(dateString).toLocaleString('zh-CN', { 
      year: 'numeric', month: 'long', day: 'numeric', 
      hour: '2-digit', minute: '2-digit' 
    });
  } catch (e) {
    return dateString; // 如果日期格式无效，返回原始字符串
  }
};

const foodDisplay = computed(() => {
  if (!props.food) {
    // 返回一个包含所有字段的默认结构，避免模板渲染错误
    return {
        id: 'N/A',
        name: '加载中...',
        categoryName: 'N/A',
        image: placeholderImageUrl,
        unit: 'N/A',
        calories: 'N/A',
        protein: 'N/A',
        fat: 'N/A',
        carbohydrate: 'N/A',
        fiber: 'N/A',
        sugar: '未提供',
        sodium: '未提供',
        cholesterol: '未提供',
        isVerified: false,
        notes: '未提供',
        source: '未提供',
        createdAt: 'N/A',
        updatedAt: 'N/A'
    };
  }
  
  const { food } = props;
  // 检查营养素是在顶层还是在 nutrition 对象下
  const nutritionSource = food.nutrition || food; // 如果 food.nutrition 存在，则用它，否则用 food 本身

  return {
    id: food._id || food.id || 'N/A',
    name: food.name || '未命名食物',
    categoryName: food.category?.name || '无分类',
    image: food.image ? apiGetFullFoodImageUrl(food.image) : placeholderImageUrl,
    unit: food.unit || '克',
    calories: food.calories !== undefined ? `${food.calories} kcal` : '未提供',
    // 从确定的营养素来源获取数据
    protein: formatNutrient(nutritionSource.protein, 'g'),
    fat: formatNutrient(nutritionSource.fat, 'g'),
    carbohydrate: formatNutrient(nutritionSource.carbohydrate, 'g'),
    fiber: formatNutrient(nutritionSource.fiber, 'g'),
    sugar: formatNutrient(nutritionSource.sugar, 'g'),
    sodium: formatNutrient(nutritionSource.sodium, 'mg'),
    cholesterol: formatNutrient(nutritionSource.cholesterol, 'mg'),
    isVerified: food.isVerified === undefined ? false : food.isVerified,
    notes: food.notes || '未提供',
    source: food.source || '未提供',
    createdAt: formatDate(food.createdAt),
    updatedAt: formatDate(food.updatedAt),
  };
});

</script>

<style scoped>
.styled-scrollbar::-webkit-scrollbar {
  width: 6px;
}
.styled-scrollbar::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}
.styled-scrollbar::-webkit-scrollbar-thumb {
  background: #c7c7c7;
  border-radius: 10px;
}
.styled-scrollbar::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
.aspect-square {
  aspect-ratio: 1 / 1;
}
</style> 